package com.panshi.controller.qa;

import com.panshi.api.*;
import com.panshi.bean.PageBean;
import com.panshi.controller.vo.AnswerAndUserVo;
import com.panshi.controller.vo.DiscussAndUserVo;
import com.panshi.controller.vo.UserAndAtricleVo;
import com.panshi.controller.vo.UserAndDiscussVo;
import com.panshi.po.*;
import com.panshi.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *问答和问题详情页面控制层
 */
@Controller
@Slf4j
@RequestMapping("question")
public class QaController {

    //注入问题接口
    @Autowired
    QuestionApi questionApi;

    //注入用户接口
    @Autowired
    UserApi userApi;

    //注入分类接口
    @Autowired
    SortApi sortApi;

    //注入回答接口
    @Autowired
    AnswerApi answerApi;

    //注入关于我们接口
    @Autowired
    IAsmeApi iAsmeApi;

    //注入友情链接接口
    @Autowired
    ILinksApi iLinksApi;

    //注入评论接口
    @Autowired
    IDiscussApi iDiscussApi;

    //注入回答审核表的接口
    @Autowired
    AnswerAuditApi answerAuditApi;

    //注入收藏接口
    @Autowired
    CollectApi collectApi;

    //注入点赞接口
    @Autowired
    PraiseApi praiseApi;


    // 问题首页 推荐、已回答、未回答
    @PostMapping("qa/{num}")
    public ModelAndView issueHomeQuery(@RequestBody PageBean pageBean, @PathVariable String num, HttpServletRequest request){

        //问题容器
        List<QuestionPO> list = null;

        //数据容器
        List<UserAndAtricleVo> user = new ArrayList<>();

        if("0".equals(num)){
            list=questionApi.findByAll(pageBean).getData();
        }else if("1".equals(num)){
            list=questionApi.findByAnswered(pageBean).getData();
        }else if("2".equals(num)){
            list=questionApi.findByUnanswered(pageBean).getData();
        }

        for (int i = 0 ; i<list.size();i++){
            UserAndAtricleVo userAndAtricleVo = new UserAndAtricleVo();
            UserPO userPO=userApi.findUserById(list.get(i).getUid()).getData();
            userAndAtricleVo.setUser(userPO);
            userAndAtricleVo.setQuestionPO(list.get(i));
            user.add(userAndAtricleVo);
        }

        request.setAttribute("qaVo", user);

        return new ModelAndView("question/qa-common");
    }

    // 根据分类名称查询问题（推荐、已回答、未回答）
    @PostMapping("sortInit/{num}")
    public ModelAndView sortInit(@RequestBody QFindBySortVO qFindBySortVO, @PathVariable String num, HttpServletRequest request){
        //问题容器
        List<QuestionPO> list = null;

        //数据容器
        List<UserAndAtricleVo> user = new ArrayList<>();
        if("0".equals(num)){
            list=questionApi.findBySortNotSold(qFindBySortVO).getData();
        }else if("1".equals(num)){
            list=questionApi.findBySortAnswer(qFindBySortVO).getData();
        }else if("2".equals(num)){
            list= questionApi.findBySortUnanswered(qFindBySortVO).getData();
        }

        for (int i = 0 ; i<list.size(); i++){
            UserAndAtricleVo userAndAtricleVo = new UserAndAtricleVo();
            UserPO userPO=userApi.findUserById(list.get(i).getUid()).getData();
            userAndAtricleVo.setUser(userPO);
            userAndAtricleVo.setQuestionPO(list.get(i));
            user.add(userAndAtricleVo);
        }

        request.setAttribute("qaVo", user);

        acme(request);
        links(request);


        return new ModelAndView("question/qa-common");
    }

    // 点击加载更多
    @PostMapping("toload")
    @ResponseBody
    public ModelAndView toload(@RequestBody PageBean pageBean, @RequestParam("num") String num,@RequestParam("sortName") String sortName, HttpServletRequest request){
        //问题容器
        List<QuestionPO> list = null;

        //数据容器
        List<UserAndAtricleVo> user = new ArrayList<>();

        if(sortName == null || "undefined".equals(sortName)){
            if("0".equals(num)){
                list=questionApi.findByAll(pageBean).getData();
            }else if("1".equals(num)){
                list=questionApi.findByAnswered(pageBean).getData();
            }else if("2".equals(num)){
                list=questionApi.findByUnanswered(pageBean).getData();
            }
        }else{
            QFindBySortVO qFindBySortVO = new QFindBySortVO();
            qFindBySortVO.setSortname(sortName);
            qFindBySortVO.setCurrentPage(pageBean.getCurrentPage());
            qFindBySortVO.setCurrentPageSize(pageBean.getCurrentPageSize());

            if("0".equals(num)){
                list=questionApi.findBySortNotSold(qFindBySortVO).getData();
            }else if("1".equals(num)){
                list=questionApi.findBySortAnswer(qFindBySortVO).getData();
            }else if("2".equals(num)){
                list= questionApi.findBySortUnanswered(qFindBySortVO).getData();
            }
        }

        for (int i = 0 ; i<list.size();i++){
            UserAndAtricleVo userAndAtricleVo = new UserAndAtricleVo();
            UserPO userPO=userApi.findUserById(list.get(i).getUid()).getData();
            userAndAtricleVo.setUser(userPO);
            userAndAtricleVo.setQuestionPO(list.get(i));
            user.add(userAndAtricleVo);
        }
        log.info("-------------------------------------------user={}",user);
        request.setAttribute("qaVo", user);

        return new ModelAndView("question/qa-common");
    }

    //跳转问题的详情页面
    @GetMapping("issue")
    public ModelAndView issue(@RequestParam String number,HttpServletRequest request){

        //存储发表问题的用户信息以及问题信息容器
        UserAndAtricleVo userAndAtricleVo = new UserAndAtricleVo();

        ModelAndView mv = new ModelAndView("question/issue");

        //获取这个用户发表的问题
        ResponseVO<QuestionPO> responseVO=questionApi.findQuestionByNumber(number);
        QuestionPO questionPO=responseVO.getData();

        //获取发表问题的用户（一个）
        UserPO userPO=userApi.findUserById(questionPO.getUid()).getData();

        //存储发表问题的用户信息和问题的信息
        userAndAtricleVo.setUser(userPO);
        userAndAtricleVo.setQuestionPO(questionPO);

        request.setAttribute("articleAnduser",userAndAtricleVo);

        //获取的回答
        IssueQueryVO issueQueryVO = new IssueQueryVO();
        issueQueryVO.setIid(questionPO.getId());
        //根据问题id获取回答的列表
        List<AnswerPO> list=answerApi.issueId(issueQueryVO).getData();

        //用户是否点赞过回答
        PraiseQueryVO praiseQueryVO=new PraiseQueryVO();
        UserPO userPOes=findEmail(request);

       // praiseQueryVO.setUid(13);
        praiseQueryVO.setNewsid(questionPO.getId());
        praiseQueryVO.setSort(1);
        praiseQueryVO.setType(1);
        PraisePO praisePO=praiseApi.findPraise(praiseQueryVO).getData();


        //存储一个回答用户信息和该用户的回答内容信息容器
        List<AnswerAndUserVo> lisss= new ArrayList<>();

        for(int i = 0; i<list.size();i++){
            AnswerAndUserVo answerAndUserVo =new AnswerAndUserVo();

            if(userPOes != null){
                praiseQueryVO.setDid(list.get(i).getId());
                praiseQueryVO.setUid(userPOes.getId());
                PraisePO praise=praiseApi.findPraise(praiseQueryVO).getData();
                if(praise != null){
                    answerAndUserVo.setIslike(1);
                }
            }


            //获取到每个回答
            answerAndUserVo.setAnswerPO(list.get(i));
            //在获取到回答的用户信息
            ResponseVO<UserPO> response=userApi.findUserById(list.get(i).getUid());
            UserPO userPOs=response.getData();
            answerAndUserVo.setAnswerPOuser(userPOs);
            lisss.add(answerAndUserVo);
        }

        log.info("回答用户和回答内容信息====================={}",lisss);
        request.setAttribute("answerAndUserVo",lisss);

        //弹窗-----------------------------------------------------
        UserPO userPOs=findEmail(request);
        mv.addObject("logicEmail",userPOs);

        //问题详情页里的相关推荐
        QFindBySortVO qFindBySortVO=new QFindBySortVO();
        qFindBySortVO.setCurrentPage(1);
        qFindBySortVO.setCurrentPageSize(5);
        qFindBySortVO.setSortname(questionPO.getSortname());
        correlation(qFindBySortVO,request);

        //问题的详情页面里加载大家都在问
        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(1);
        pageBean.setCurrentPageSize(10);
        findByBrowse(pageBean,request);


        PageVO pageVO = new PageVO();
        pageVO.setSize(10);
        pageVO.setCurrenPage(1);
        sortQuery(pageVO,request);

        acme(request);
        links(request);

        return mv;

    }

    //跳转问题首页
    @GetMapping("home")
    public String qa(HttpServletRequest request){
        //加载分类
        PageVO pageVO=new PageVO ();
        pageVO.setCurrenPage(1);
        pageVO.setSize(10);
        sortQuery(pageVO,request);

        //加载大家都在问
        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(1);
        pageBean.setCurrentPageSize(10);
        findByBrowse(pageBean,request);

        //加载关于我们
        acme(request);
        //加载友情链接
        links(request);

        return "question/qa";
    }

    //点击分类名称跳转页面
    @GetMapping("qa")
    public String qa(@RequestParam String sortname, Model model,HttpServletRequest request){

        model.addAttribute("sortname",sortname);
        PageVO pageVO =new PageVO();

        //点击分类名称之后的分类
        pageVO.setCurrenPage(1);
        pageVO.setSize(10);
        sortQuery(pageVO,request);

        //点击分类名称之后的大家都在问功能
        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(1);
        pageBean.setCurrentPageSize(10);
        findByBrowse(pageBean,request);

        return "question/qa";
    }

    //分类
    @PostMapping("sort")
    public ModelAndView sortQuery(PageVO pageVO,HttpServletRequest request){

        ModelAndView mv = new ModelAndView("comment/middle");

        ResponseVO responseVO=sortApi.sortQuery(pageVO);

        List<SortPO> list= (List<SortPO>) responseVO.getData();

        request.setAttribute("SortPO",list);

        acme(request);
        links(request);

        return mv;

    }

    //大家都在问功能
    @PostMapping("findByBrowse")
    public ModelAndView findByBrowse(PageBean pageBean,HttpServletRequest request){

        log.info("pageBean======{}",pageBean);

        ModelAndView mv = new ModelAndView("comment/side");

        ResponseVO responseVO=questionApi.findByBrowse(pageBean);

        List<SortPO> list= (List<SortPO>) responseVO.getData();

        request.setAttribute("when",list);

        return mv;

    }

    //问题详情页里的相关推荐
    @PostMapping("correlation")
    public ModelAndView correlation(QFindBySortVO qFindBySortVO,HttpServletRequest request){

        ModelAndView mv = new ModelAndView("question/correlation-commom");

        ResponseVO responseVO=questionApi.findBySortNotSold(qFindBySortVO);

        List<SortPO> list= (List<SortPO>) responseVO.getData();

        request.setAttribute("correlation",list);

        return mv;

    }

    //问题首页加载关于我们
    @PostMapping("as")
    public ModelAndView acme(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("comment/button");
        PageBeanVo pageBeanVo =new PageBeanVo();
        pageBeanVo.setCurrenPage(1);
        pageBeanVo.setPageSize(10);

        //获取关于我们的列表
        List<AsmePO> list= iAsmeApi.queryAsmePostBody(pageBeanVo).getData();

        //存放每个对象的容器
        List<AsmePO>  linksAndMeVoList = new ArrayList<>();

        log.info("获取关于我们的列表==============================={}",list);

        for (int i=0; i<list.size(); i++){
            linksAndMeVoList.add(list.get(i));
        }
        request.setAttribute("meVo",list);
        return mv;
    }

    //问题首页加载友情链接
    @PostMapping("links")
    public ModelAndView links(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("comment/button");
        PageBeanVo pageBeanVo =new PageBeanVo();
        pageBeanVo.setCurrenPage(1);
        pageBeanVo.setPageSize(10);

        //获取关于我们的列表
        List<LinksPO> list= iLinksApi.queryLinksPostBody(pageBeanVo).getData();

        log.info("queryLinksPostBody======{}",iLinksApi.queryLinksPostBody(pageBeanVo).getData());

        //存放每个对象的容器
        List<LinksPO>  linksAndMeVoList = new ArrayList<>();

        for (int i=0; i<list.size(); i++){
            linksAndMeVoList.add(list.get(i));
        }
        request.setAttribute("linksVo",list);
        return mv;
    }


    //问题详情里的收藏问题
    @PostMapping("collectIssue")
    @ResponseBody
    public Integer collectIssue(@RequestBody QuestionUpdateVO questionUpdateVO,HttpServletRequest request){

        //先根据问题编号查询出问题id
        QuestionPO questionPO=questionApi.findQuestionByNumber(questionUpdateVO.getNumber()).getData();
        //增加进收藏表
        CollectAddVo collectAddVo = new CollectAddVo();
        UserPO userPO=findEmail(request);
        if(userPO == null){
            return 4;
        }

        collectAddVo.setNid(questionPO.getId());
        collectAddVo.setUid(userPO.getId());
        collectAddVo.setType(1);
        collectAddVo.setDate(new Date());

        CollectGroupQueryVo collectGroupQueryVo = new CollectGroupQueryVo();
        collectGroupQueryVo.setNid(questionPO.getId());
        collectGroupQueryVo.setUid(userPO.getId());
        collectGroupQueryVo.setType(1);
        CollectPo collectPo=collectApi.groupQuery(collectGroupQueryVo).getData();
        if(collectPo == null){
            questionUpdateVO.setCollect(1);
            log.info("进来了收藏问题questionUpdateVO============{}",questionUpdateVO);
            Integer integer=questionApi.questionUpdate(questionUpdateVO).getData();

            Integer integers=collectApi.addCollect(collectAddVo).getData();
            if(integers == 1){
                return integer;
            }else{
                return 2;
            }
        }
        return 3;
    }

    //问题详情里的回答点赞
    @PostMapping("addTags")
    @ResponseBody
    public Integer addTags(@RequestBody PraiseAddVO praiseAddVO,HttpServletRequest request){

        log.info("praiseAddVO============{}",praiseAddVO);

        UserPO userPO=findEmail(request);
        if(userPO == null){
            return 2;
        }
        praiseAddVO.setUid(userPO.getId());
        PraiseQueryVO praiseQueryVO=new PraiseQueryVO();
        BeanUtils.copyProperties(praiseAddVO,praiseQueryVO);

        PraisePO praisePO=praiseApi.findPraise(praiseQueryVO).getData();
        if(praisePO == null){
            praiseApi.praiseAdd(praiseAddVO);
            answerApi.countTags(praiseAddVO.getDid()).getData();
        }else{
            return 0;
        }

        return 1;
    }

    //问题详情里的回答点踩
    @GetMapping("tread/{id}")
    @ResponseBody
    public Integer tread(@PathVariable Integer id){
        log.info("id============{}",id);
        Integer integer=answerApi.countTread(id).getData();
        return integer;
    }

    //点击评论后显示评论
    @PostMapping("nidQuery")
    public ModelAndView query(@RequestBody QueryFidesVO queryFidesVO,HttpServletRequest request){

        ModelAndView mv = new ModelAndView("question/issue-commom-commom");

        queryFidesVO.setCurrentPage(1);
        queryFidesVO.setPageSize(6);

        //获取评论的列表
        List<DiscussPO> list=iDiscussApi.queryFidDiscussPostBody(queryFidesVO).getData();

        //存放评论的用户和该用户评论的内容
        List<DiscussAndUserVo> duserList = new ArrayList<>();
        DiscussAndUserVo discussAndUserVo =null;
        for (int i=0; i<list.size();i++){
            discussAndUserVo= new DiscussAndUserVo();
            UserPO userPO=userApi.findUserById(list.get(i).getUid()).getData();
            discussAndUserVo.setPinUser(userPO);
            discussAndUserVo.setDiscussPO(list.get(i));
            duserList.add(discussAndUserVo);
        }

        log.info("点击评论后显示评论={}",duserList);

        request.setAttribute("discusesUser",duserList);
        return mv;
    }

    //对回答进行评论
    @PostMapping("addDisscuss")
    @ResponseBody
    public ResponseVO addDisscuss(@RequestBody AddDiscussVO addDiscussVO,HttpServletRequest request){
        log.info("AddDiscussVO===={}",addDiscussVO);
        UserPO userPO=findEmail(request);
        addDiscussVO.setUid(userPO.getId());

        ResponseVO responseVO = new ResponseVO();

        if(addDiscussVO.getUid()==null){
            responseVO.setSuccess(false);
            responseVO.setCode("500");
            responseVO.setMsg("请先登录");
            responseVO.setData(-1);
            return responseVO;
        }

        addDiscussVO.setDates(new Date());
        addDiscussVO.setCreatedate(new Date());
        Integer integers=iDiscussApi.addDiscussPostBody(addDiscussVO).getData();

        //评论完后回答表里的评论数+1
        answerApi.countAiscuss(addDiscussVO.getNid());

        responseVO.setSuccess(true);
        responseVO.setCode("200");
        responseVO.setMsg("评论成功");
        responseVO.setData(integers);

        return  responseVO;
    }

    //发表回答到回答审核表
    @PostMapping("addAnswerAudit")
    @ResponseBody
    public Integer addAnswerAudit(@RequestBody AnswerAuditAddVO answerAuditAddVO,HttpServletRequest request){
        log.info("发表回答到回答审核表进来了======{}",answerAuditAddVO);
        UserPO userPO=findEmail(request);
        answerAuditAddVO.setUid(12);
        answerAuditAddVO.setCreatedate(new Date());
        answerAuditAddVO.setAnswerno(UUID.randomUUID().toString());
        Integer integer=answerAuditApi.addAnswerAudit(answerAuditAddVO).getData();
        return  integer;

    }

    //点击查看回复评论
    @PostMapping("fidQueryDiscuss")
    @ResponseBody
    public ModelAndView fidQueryDiscuss(@RequestBody QueryFidVO queryFidVO,HttpServletRequest request){

        ModelAndView mv = new ModelAndView("question/issue-ReplyComments");

        //获取到回复这个评论的列表
        List<DiscussPO> list=iDiscussApi.queryFidesDiscussPostBody(queryFidVO).getData();

        UserAndDiscussVo userAndDiscussVo = null;

        //存放回复评论的评论内容和该用户的信息容器
        List<UserAndDiscussVo> userAndDiscussList = new ArrayList<>();

        for (int i=0; i<list.size();i++){
            userAndDiscussVo=new UserAndDiscussVo();
            userAndDiscussVo.setDiscussPO(list.get(i));
            userAndDiscussVo.setDiscussUser(userApi.findUserById(list.get(i).getUid()).getData());
            userAndDiscussList.add(userAndDiscussVo);
        }

        log.info("userAndDiscussList================{}",userAndDiscussList);

        request.setAttribute("userAndDiscuss",userAndDiscussList);
        return mv;
    }

    //对评论进行回复
    @PostMapping("addReplyDisscuss")
    @ResponseBody
    public ResponseVO addReplyDisscuss(@RequestBody AddDiscussVO addDiscussVO,HttpServletRequest request){


        UserPO userPO=findEmail(request);
        addDiscussVO.setUid(userPO.getId());
        addDiscussVO.setTypees(1);

        ResponseVO responseVO = new ResponseVO();

        if(addDiscussVO.getUid()==null){
            responseVO.setSuccess(false);
            responseVO.setCode("500");
            responseVO.setMsg("请先登录");
            responseVO.setData(-1);
            return responseVO;
        }

        log.info("AddDiscussVO===={}",addDiscussVO);

        Integer integers=iDiscussApi.addDiscussPostBody(addDiscussVO).getData();

        iDiscussApi.countReply(addDiscussVO.getFid());
        responseVO.setSuccess(true);
        responseVO.setCode("200");
        responseVO.setMsg("回复成功");
        responseVO.setData(integers);

        return  responseVO;
    }

    //对评论回复的点赞
    @PostMapping("addDiessTags")
    @ResponseBody
    public Integer addDiessTags(PraiseAddVO praiseAddVO,HttpServletRequest request){

        log.info("praiseAddVO============{}",praiseAddVO);
        UserPO userPO=findEmail(request);
        if(userPO == null){
            return 2;
        }
        praiseAddVO.setUid(userPO.getId());
        praiseAddVO.setDid(praiseAddVO.getDid());
        AnswerPO answerPO=answerApi.byIdAnswer(praiseAddVO.getNewsid()).getData();

        //获取问题id
        praiseAddVO.setNewsid(answerPO.getIid());

        PraiseQueryVO praiseQueryVO=new PraiseQueryVO();
        BeanUtils.copyProperties(praiseAddVO,praiseQueryVO);
        PraisePO praisePO =praiseApi.findPraise(praiseQueryVO).getData();
        if(praisePO == null){
            praiseApi.praiseAdd(praiseAddVO);
            Integer integer=iDiscussApi.countTags(praiseAddVO.getDid()).getData();
            return 1;
        }

        return 0;
    }

    //从session中获取登录后的用户id
    public UserPO findEmail(HttpServletRequest request){
        String email= (String) request.getSession().getAttribute("logicEmail");
        if(email!=null){
            return  userApi.findUserByEmail(email).getData();
        }
        return null;
    }

}
